<template>
    <div>
        <h1>未保存关闭页面提示示例</h1>
        <div>
            使用办法：文本框中输入一些内容，刷新页面有提示，保存后刷新页面无提示。
        </div>
        <input v-model="inputValue" placeholder="输入一些内容" />
        <button @pointerdown="saveData">保存</button>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';

const inputValue = ref('');
const isDataSaved = ref(true);

const saveData = () => {
    isDataSaved.value = true;
    console.log('数据已保存');
};

const handleBeforeUnload = (event: any) => {
    if (!isDataSaved.value) {
        event.preventDefault();
        event.returnValue = '';
        return '';
    }
};

onMounted(() => {
    window.addEventListener('beforeunload', handleBeforeUnload);
});

onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
});

watch(inputValue, (newVal) => {
    if (newVal) {
        isDataSaved.value = false;
    }
});
</script>
